package no.uib.hplims;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.io.Serializable;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import no.uib.hplims.jobs.DatabaseBackup;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.SimpleScheduleBuilder.*;
import static org.quartz.DateBuilder.*;
import org.vaadin.appfoundation.persistence.facade.FacadeFactory;

public class MyContextListener implements ServletContextListener, Serializable {

	private static final long serialVersionUID = 9207204524234668519L;

	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void contextInitialized(ServletContextEvent arg0) {
		try {
			// Register facade
			FacadeFactory.registerFacade("hplims-persistence", true);

			// Set the secret salt value for passwords, this value shouldn't be
			// changed after the application has been take into use
			System.setProperty("authentication.password.salt",
					"@6+5Y0yJ24+L4(04/<[2X<U-69z]!=");

			// The minimum length for passwords is six characters
			System.setProperty("authentication.password.validation.length", "6");

			// Require that all passwords have lower and upper case letters and
			// additionally at least one numeric character. Special characters
			// are
			// not required.
			System.setProperty(
					"authentication.password.validation.lowerCaseRequired",
					"false");
			System.setProperty(
					"authentication.password.validation.upperCaseRequired",
					"false");
			System.setProperty(
					"authentication.password.validation.numericRequired",
					"false");
			System.setProperty(
					"authentication.password.validation.specialCharacterRequired",
					"false");
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			// Grab the Scheduler instance from the Factory
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

			// and start it off
			scheduler.start();

			JobDetail job = newJob(DatabaseBackup.class).withIdentity("job1",
					"group1").build();
			
			SimpleTrigger trigger = (SimpleTrigger) newTrigger()
					.withIdentity("trigger1")
					.startAt(dateOf(1, 0, 0))
					.withSchedule(
							simpleSchedule().withIntervalInHours(24)
									.repeatForever()).build();

			scheduler.scheduleJob(job, trigger);

			// scheduler.shutdown();

		} catch (SchedulerException se) {
			se.printStackTrace();
		}
	}

}
